<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 质量风险监控记录 -->
    <div
      id="base-breadcrumb"
      style="position: relative; z-index: 1"
    >
      <!-- 搜索 -->
      <searchData
        ref="searchData"
        :search-data="searchArr"
        @search2="search2"
      />
      <!-- 表格 -->
      <a-card :bordered="false">
        <!-- <title-name title="列表"></title-name> -->
        <div class="mb12">
          <excel ref="exportSelect" fileName="质量风险监控记录选中" is-click-generate="false" :transformTimeKey="[]">
            <a-button
              slot="excelBtn"
              class="excelBtn"
              v-btnPermission="'qm_059_sexp_02'"
              :loading="exportExcelLoading[0]"
              icon="download"
              :disabled="selectedRowKeys.length < 1"
              type="primary"
              @click="exportExcel(0)"
            >
            选中导出列表
            </a-button>
          </excel>
          <excel
            ref="exportAll"
            fileName="质量风险监控记录全部"
            is-click-generate="false"
            :transformTimeKey="[]"
          >
            <a-button
              slot="excelBtn"
              class="excelBtn"
              v-btnPermission="'qm_059_aexp_03'"
              :loading="exportExcelLoading[1]"
              icon="cloud-download"
              type="primary"
              @click="exportExcel(1)"
            >
              全部导出列表
            </a-button>
          </excel>
          <a-button
            v-btnPermission="'qm_059_sexp_04'"
            :loading="exportWordLoading[1]"
            icon="download"
            class="ml12"
            :disabled="selectedRowKeys.length < 1"
            type="primary"
            @click="exportWord(1)"
          >
            选中导出风险信息
          </a-button>
          <a-button
            v-btnPermission="'qm_059_aexp_05'"
            :loading="exportWordLoading[0]"
            icon="cloud-download"
            class="ml12"
            type="primary"
            @click="exportWord(0)"
          >
            全部导出风险信息
          </a-button>
        </div>
        <a-spin :spinning="spinning" tip="记录类别加载中..." style="width:100%">
            <!-- 记录类别 -->
          <a-tabs v-if="recordCheckTypeIdList.length > 0" :animated="false" v-model="recordCheckTypeId" @change="tabsChange" size="large">
              <!-- 记录类别列表 -->
              <a-tab-pane v-for="item in recordCheckTypeIdList" :key="item.id" :tab="item.name"></a-tab-pane>
          </a-tabs>
        </a-spin>
        <!--表格-->
        <list-table
          ref="table"
          size="small"
          rowKey="id"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          :columns="columns"
          :isEportIndex="true"
          :request="loadData"
          :isShowCountBar="false"
          show-size-changer
          show-quick-jumper
          showPagination="auto"
        >
          <span
            slot="sort"
            slot-scope="text, record, index"
          >{{ index + 1 }}</span>
          <more-button
            slot="actions"
            slot-scope="text, record"
          >
            <a
              v-btn-permission="'qm_059_loo_01'"
              @click="handleManage(2, record)"
            >查看</a>
            <a
              v-if="(record.verifierId == $userInfo().id || record.verifierId == $userInfo().employee.id) && (record.result ? (record.result.code != '0' && record.result.code != '1'): true )  "
              @click="handleManage(3, record)"
            >验证</a>
          </more-button>
        </list-table>
      </a-card>
    </div>
  </base-breadcrumb>
</template>

<script>
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import OrgTreeSelect from '@/components/OrgTreeSelect'
import SelectProjectType from '@/components/Select/SelectProjectType' // 工程类别
import MoreButton from '@/components/MoreButton' // 多按钮容器
import BasePage from '@/views/basePage'
import Selector from '@/components/Select/Selector' // 选择器
import { qualityTypeLabel } from '@/api/quality/projectDivision' // api
import { monitoringRecords } from '@/api/quality/risk/monitoringRecords'
const searchArr = [
  // 搜索框
  {
      name: '所属单位',
      valueKey: 'searchQuery',
      type: OrgTreeSelect,
  },
  {
      name: '风险等级',
      valueKey: 'riskLevelId',
      type: Selector,
      attrs: {
        selectType: '59'
      },
      filterFn(item) {
        // 不要整改超时
        return item.code !== '4'
      }
  },
  {
      name: '生效日期',
      value: 'takeEffectDate',
      type: 'dateRange',
      rangeFormat: ['takeEffectStartDate', 'takeEffectEndDate']
  },
  {
      name: '检查时限',
      value: 'timeLimitDate',
      type: 'dateRange',
      rangeFormat: ['timeLimitStartDate', 'timeLimitEndDate']
  },
  {
    name: '检查人',
    type: SelectPersonByProject,
    valueKey: 'checkerIds',
    attrs: {
      mode: 'multiple',
      isShowUnit: false,
      placeholder: '请输入'
    }
  },
  {
    name: '验证人',
    type: SelectPersonByProject,
    valueKey: 'verifierIds',
    attrs: {
      mode: 'multiple',
      isShowUnit: false,
      placeholder: '请输入'
    },
  },
  {
    name: '工程部位',
    type: 'input',
    value: 'projectPosition'
  },
  {
    name: '风险名称',
    type: 'input',
    value: 'name'
  },
  {
      name: '完成时间',
      value: 'completeDate',
      type: 'dateRange',
      rangeFormat: ['completeStartDate', 'completeEndDate']
  },
  {
    name: '工程类别',
    type: SelectProjectType,
    valueKey: 'projectTypeId',
    showStop: true,
  },
  
]
export default {
  name: 'a' + Date.now(),
  extends: new BasePage(),
  components: {
    MoreButton
  },
  data() {
    this.searchArr = searchArr
    return {
      spinning: false,
      recordCheckTypeId: '',
      selectedRowKeys: [],
      selectedRows: [],
      recordCheckTypeIdList: [],
      exportExcelLoading: {0: false, 1: false}, // 导出加载控件
      exportWordLoading: {0: false, 1: false}, // 导出加载控件
      visible: false,
      // 表格加载
      queryParam: {}, // 查询参数
      totalSize: 0,
      api: monitoringRecords,
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam, {recordCheckTypeId: this.recordCheckTypeId})
        return this.api.getList(requestParameters).then((res) => {
          if (res.data) {46395
            res.data = res.data.map(item => {
              item.resultName = item.result ? item.result.name : ''
              item.levelName = item.level ? item.level.name : ''
              return item
            })
            this.totalSize = res.totalSize
          }
          return res
        })
      }
    }
  },
  computed: {
    columns() {
      let list = [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          scopedSlots: { customRender: 'sort' }
        },
        {
          title: '分公司',
          ellipsis: true,
          dataIndex: 'branchCompanyName'
        },
        {
          title: '项目名称',
          ellipsis: true,
          dataIndex: 'projectName'
        },
        {
          title: '风险名称',
          ellipsis: true,
          dataIndex: 'name'
        },
        {
          title: '工程部位',
          ellipsis: true,
          dataIndex: 'projectPosition'
        }
      ]
      if (this.recordCheckTypeIdList.length > 0) {
        if (this.recordCheckTypeId != this.recordCheckTypeIdList[this.recordCheckTypeIdList.length - 1].id) {
          list.push({
            title: '复核风险等级',
            ellipsis: true,
            dataIndex: 'levelName',
          })
        }
      } else {
        list.push({
          title: '复核风险等级',
          ellipsis: true,
          dataIndex: 'levelName',
        })
      }
      const other = [
        {
          title: '监控停止点',
          ellipsis: true,
          dataIndex: 'newMonitorEndpoint'
        },
        {
          title: '完成时间',
          ellipsis: true,
          dataIndex: 'newTakeEffectDate'
        },
        {
          title: '验证人',
          ellipsis: true,
          dataIndex: 'newVerifierName'
        },
        {
          title: '检查人',
          ellipsis: true,
          dataIndex: 'newCheckerName'
        },
        {
          title: '任务总数',
          ellipsis: true,
          dataIndex: 'newTaskNum'
        },
        {
          title: '任务完成数量',
          ellipsis: true,
          dataIndex: 'newTaskEndNum'
        },
        {
          title: '验证结果',
          dataIndex: 'resultName',
        },
        {
          title: '操作',
          dataIndex: 'actions',
          width: 150,
          align: 'center',
          scopedSlots: { customRender: 'actions' }
        }
      ]
      list = list.concat(other)
      return list
    }
  },
  mounted() {
    this.getCheckType()
    this.$refs.exportSelect.tableToExcelFile(this.$refs.table)
    this.$refs.exportAll.tableToExcelFile(this.$refs.table)
  },
  methods: {
     /**
     * 导出风险信息
     * @param parameter
     */
      async exportWord(type){
        if (type && this.selectedRowKeys.length === 0) {
          this.$message.warning('请选择需要导出的数据')
          return false
        }
        let params = { }
        if (type) {
          params = { ids: this.selectedRowKeys }
        }
        let expqueryParam = Object.assign({}, params, this.$refs.searchData.form.getFieldsValue())
        this.exportWordLoading[type] = true
        this.api.impRecords(expqueryParam).then(res => {
          if (res.code === 200) {
            // 格式化名称，防止重名被覆盖
            res.data.forEach((i, idx) => {
              i.name = Number(idx) + 1 + '.' + i.name
            })
            this.exportPointInfo(res.data, '风险信息')
          }
        }).finally(() => {
          setTimeout(() => {
            this.exportWordLoading[type] = false
          }, 500);
        })
    },
    /**
     * @description: 搜索
     * @param {*} value：表单对象
     */
    search2(value) {
      if (value) {
        if (value.takeEffectDate) {
          if (value.takeEffectDate.length > 0) {
            value.takeEffectStartDate = value.takeEffectDate[0].format('YYYY-MM-DD')
            value.takeEffectEndDate = value.takeEffectDate[1].format('YYYY-MM-DD')
          }
          delete value.takeEffectDate
        }
        if (value.timeLimitDate) {
          if (value.timeLimitDate.length > 0) {
            value.timeLimitStartDate = value.timeLimitDate[0].format('YYYY-MM-DD')
            value.timeLimitEndDate = value.timeLimitDate[1].format('YYYY-MM-DD')
          }
          delete value.timeLimitDate
        }
        if (value.completeDate) {
          if (value.completeDate.length > 0) {
            value.completeStartDate = value.completeDate[0].format('YYYY-MM-DD')
            value.completeEndDate = value.completeDate[1].format('YYYY-MM-DD')
          }
          delete value.completeDate
        }
        this.queryParam = value
      }
      this.$refs.table.refresh(true)
    },
    tabsChange() {
      this.$refs.table.refresh(true)
    },
    /**
     * @description: 跳转操作页
     * @param {*} type：操作类型： 0 填报；1调整；2 查看；3 验证；4 生成整改单
     * @param {*} id：业务id
     */
    handleManage(type, record) {
      if (record) {
        // qualityriskIdentificationmonitoringRecordsReportingInfo 查看（上报风险）
        // qualityriskIdentificationmonitoringRecordsMonitoringInfo 查看（重点监管风险)
        if (record.recordCheckType && record.recordCheckType.code) {
          const code = record.recordCheckType.code
          this.$router.push({
            name: code == '1' ? 'qualityriskIdentificationmonitoringRecordsMonitoringInfo': 'qualityriskIdentificationmonitoringRecordsReportingInfo',
            query: {
              id: record.id, // 业务id
              sourceId: record.sourceId,
              editModel: type, // 操作类型
            }
          })
        }
        
      }
    },
    //获取检查类别
    getCheckType(){
      this.spinning = true
      qualityTypeLabel({type: 60}).then((res)=>{
        if(res.code==200){
          this.recordCheckTypeIdList = res.data
          this.recordCheckTypeIdList.unshift({id: '', name: '全部'})
          this.recordCheckTypeId = ''
        }
        this.spinning = false
      }).catch(() => {
        this.spinning = false
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    /**
     * @description: 导出word
     * @param {*} datas：选中项
     */
     exportExcel(index) {
      if (index) {
        this.exportExcelLoading[1] = true
        const requestParameters = Object.assign({}, {pageNo: 1, pageSize: this.totalSize}, this.queryParam, {recordCheckTypeId: this.recordCheckTypeId})
        return this.api.getList(requestParameters).then((res) => {
          if (res.data) {
            res.data = res.data.map(item => {
              item.resultName = item.result ? item.result.name : ''
              item.levelName = item.level ? item.level.name : ''
              return item
            })
            this.$refs.exportAll.setDataAndGenerate(res.data)
          }
        }).finally(() => {
          setTimeout(() => {
            this.exportExcelLoading[1] = false
          }, 500)
        })
      } else {
        if (this.selectedRows.length > 0) {
          this.exportExcelLoading[0] = true
          this.$refs.exportSelect.setDataAndGenerate(this.selectedRows)
          setTimeout(() => {
            this.exportExcelLoading[0] = false
          }, 500)
        } else {
          this.$message.warning('请选择需要导出的数据')
        }
      }
    },
  }
}
</script>